package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pojo.User;
import dao.UserHandle;
import db.DBUtil;

public class UserHandleImpl implements UserHandle {

	@Override
	public int addUser(User user) {
		String sql = "insert into t_user(id,uname,salary,birth,sex,avatar) values(seq03.nextval,?,?,?,?,?)";
		Connection con=null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getUname());
			pst.setDouble(2, user.getSal());
			pst.setDate(3, new java.sql.Date(user.getBirth().getTime()));
			pst.setString(4, user.getSex());
			pst.setBytes(5, user.getAvatar());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		}
		return m;
	}

	@Override
	public List<User> loadUsers() {
		List<User> list=new ArrayList<User>();
		String sql = "select * from t_user";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			
			rs = pst.executeQuery();
			while (rs.next()) {
				User u = new User();
				String uname = rs.getString("uname");
				double sal = rs.getDouble("salary");
				java.sql.Date date = rs.getDate("birth");
				Date birth = new Date(rs.getDate("birth").getTime());
				String sex = rs.getString("sex");
				byte[] b = rs.getBytes("avatar");
				int id=rs.getInt("id");
				u.setId(id);
				u.setUname(uname);
				u.setSal(sal);
				u.setBirth(birth);
				u.setSex(sex);
				u.setAvatar(b);
				list.add(u);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return list;
	}
	
	public User loadUser(String username) {
		List<User> list=new ArrayList<User>();
		String sql = "select * from t_user";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		User u = new User();
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			
			rs = pst.executeQuery();
			
			while (rs.next()) {
				String uname = rs.getString("uname");
				double sal = rs.getDouble("salary");
				java.sql.Date date = rs.getDate("birth");
				Date birth = new Date(rs.getDate("birth").getTime());
				String sex = rs.getString("sex");
				byte[] b = rs.getBytes("avatar");
				int id=rs.getInt("id");
				u.setId(id);
				u.setUname(uname);
				u.setSal(sal);
				u.setBirth(birth);
				u.setSex(sex);
				u.setAvatar(b);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return u;
	}

}
